﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using FractalistWX.Tool;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace FractalistWX.Manage
{
    public partial class UploadFile : System.Web.UI.Page
    {
        string cId = "";
        string file = "";
        string type = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            cId = Tools.SafeSql(Tools.CheckVar(Request["cid"], "PicTB"));
            file = Tools.SafeSql(Tools.CheckVar(Request["file"], "res"));
            //1pc轮播图，2手机轮播图
            type = Tools.SafeSql(Tools.CheckVar(Request["file"], "0"));
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = this.FileUpload1.PostedFile.FileName;
                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }               
                //获得绝对路径
                string applicationPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "UpFiles/" + file + "/";

                string imageName = FileUpload1.FileName;
                string ext= fileName.Substring(imageName.LastIndexOf("."), imageName.Length - imageName.LastIndexOf("."));
                if (ext == ".jpg" || ext == ".gif" || ext == ".png" || ext == ".jpeg" || ext == ".bmp")
                {
                    //设置每次上传的图片文件名的相对路径
                    string TimeStr = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string AllFileName = TimeStr + FileUpload1.PostedFile.ContentLength.ToString() + imageName.Substring(imageName.LastIndexOf("."), imageName.Length - imageName.LastIndexOf("."));
                    AllFileName = AllFileName.ToLower();
                    string imageTempPath = applicationPath + AllFileName;


                    Bitmap bitmpa = new Bitmap(this.FileUpload1.PostedFile.InputStream);

                    Bitmap saveImg = new Bitmap(bitmpa.Width, bitmpa.Height);
                    Graphics g = Graphics.FromImage(saveImg);
                    // 插值算法的质量   
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(bitmpa, new Rectangle(0, 0, bitmpa.Width, bitmpa.Height), new Rectangle(0, 0, bitmpa.Width, bitmpa.Height), GraphicsUnit.Pixel);
                    g.Dispose();
                    saveImg.Save(imageTempPath);

                    //FileUpload1.PostedFile.SaveAs(imageTempPath);
                    Response.Write("<script> window.parent.document.getElementById('" + cId + "').value = '"+file+"/"+ AllFileName + "';</script>");
                }
                else
                {
                    Response.Write("<script> alert('文件格式不对');</script>");
                }
            }
            catch
            {

            }
        }
    }
}